package com.shj.em.aa.service;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.shj.em.aa.dto.UserSearchDTO;
import com.shj.em.aa.entity.Role;
import com.shj.em.aa.entity.User;
import com.shj.em.aa.mapper.UserMapper;
import com.shj.em.util.MD5Utils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author Shen Huang Jian
 * @since 2018-06-25
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {

    @Autowired
    private UserMapper userMapper;

    public Page<User> queryUserPage(UserSearchDTO searchDTO){
        Page<User> page = new Page<>(searchDTO.getPageNo(), searchDTO.getPageSize());
        List<User> list = userMapper.queryUserPage(page, searchDTO);
        return page.setRecords(list);
    }

    public User findByUserId(String userId){
        return userMapper.findByUserId(userId);
    }

    public List<User> getUsersByRoleId(Long roleId){
        return userMapper.getUsersByRoleId(roleId);
    }

    public List<User> getUsersUnassignedRoleId(Long roleId){
        return userMapper.getUsersUnassignedRoleId(roleId);
    }

    public List<User> getAllUsers(){
        Wrapper<User> userWrapper = new EntityWrapper<>();
        userWrapper.eq("del_flag", 0);
        return userMapper.selectList(userWrapper);
    }

    public String changePwd(String userId, String password, String oldPwd) {
        User usr = userMapper.findByUserId(userId);
        if(usr == null){
            return "用户帐号错误。";
        }
        if(oldPwd != null){
            String encrypt = MD5Utils.encrypt(userId, oldPwd);
            if(!encrypt.equals(usr.getPassword())){
                return "旧密码错误。";
            }
        }
        usr.setPassword(MD5Utils.encrypt(userId, password));
        userMapper.updateById(usr);
        return "";

    }

    public String resetPwd(String userId) {
        User usr = userMapper.findByUserId(userId);
        if(usr == null){
            return "用户帐号错误。";
        }
        usr.setPassword(MD5Utils.encrypt(userId, MD5Utils.DEFAULT_PWD));
        userMapper.updateById(usr);
        return "";
    }

    public void resetAllPwd(){
        Wrapper<User> wrapper = new EntityWrapper<>();
        wrapper.eq("del_flag", 0);
        List<User> users = userMapper.selectList(wrapper);
        for(User user : users){
            user.setPassword(MD5Utils.encrypt(user.getUserId(), "111111"));
            userMapper.updateById(user);
        }
    }
}
